import type {CipherMode} from 'sm-crypto';
import {sm2, sm3, sm4} from 'sm-crypto';

export function doEncryptBySM2(puk: string | undefined | null, msgString: string): string {
    let msg: string = msgString;
    let cipherMode: CipherMode = 1; // 1 - C1C3C2，0 - C1C2C3，默认为1
    if (!puk) {
        return '';
    }
    let encryptData = sm2.doEncrypt(msg, puk, cipherMode); // 加密结果
    encryptData = '04' + encryptData;
    return encryptData;
}

export function doDecryptByBySM2(prk: string | undefined | null, msgString: string): string {
    let msg: string = msgString;
    let cipherMode: CipherMode = 1; // 1 - C1C3C2，0 - C1C2C3，默认为1
    if (!prk) {
        return '';
    }
    // 加密结果
    return sm2.doDecrypt(msg, prk, cipherMode);
}

export function doEncryptBySM3(msgString: string): string {
    // 杂凑
    return sm3(msgString);
}

//sm4用法
export function doEncryptBySM4(msgString: string, sm4Key: string): string {
    sm4Key = sm4Key || '12345678901234567890123456789012';
    //后台使用Padding.PKCS5Padding 配套解密
    //加密
    return sm4.encrypt(msgString, sm4Key);
}

export function decryptBySM4(msgString: string, sm4Key: string | null | undefined): string {
    if (!sm4Key) {
        return msgString;
    }
    //加密
    return sm4.decrypt(msgString, sm4Key);
}

export function genSm4Key(): string {
    let sm4Key: string = '';
    const chars: string = '0123456789abcdef';
    const maxPos: number = chars.length;
    for (let i = 0; i < 32; i++) {
        sm4Key += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return sm4Key;
}
